/*
 * Created on 12 juil. 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package fr.jade.event.dispatcher;

import java.util.Hashtable;
import java.util.Map;

import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.BindingController;
import org.objectweb.fractal.api.control.IllegalBindingException;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;

import fr.jade.base.JadeBaseComponent;
import fr.jade.event.Event;
import fr.jade.event.EventHandler;
import fr.jade.util.JadeException;


public class DispatcherImpl extends JadeBaseComponent implements EventHandler, BindingController{
  
	// binding
  protected static final String handlersItfNamePrefix = "event-out";
	protected Map<String, EventHandler> handlers = new Hashtable<String, EventHandler>(); 

	public synchronized void handleEvent(final Event e) throws JadeException{
	  assert e != null : "Event is null";
	  assert e.getEventHeader() != null : "Malformed event (no header)";
	  assert e.getEventBody() != null : "Malformed event (no body)";
	  
		log("Handle "+ e.getEventHeader() +" event");
		for (final EventHandler eh : handlers.values()){
			new Thread () {
				public void run (){
					try{
						eh.handleEvent(e);
					}catch(Exception e1){
						log(e1);
					}
				}
			}.start ();
		}
	}

	// Binding Controller
	
	public void bindFc(String itfName, Object itfValue) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
		if (itfName.startsWith(handlersItfNamePrefix)) {
			handlers.put(itfName, (EventHandler)itfValue);
		}else {
			super.bindFc(itfName, itfValue);
		}
	}

	public String[] listFc() {
		return super.concat(handlers.keySet(), super.listFc());
	}

	public Object lookupFc(String itfName) throws NoSuchInterfaceException {
		if (itfName.startsWith(handlersItfNamePrefix)) {
		  //if(!handlers.containsKey(itfName)) throw new NoSuchInterfaceException(itfName);
			return handlers.get(itfName);
		}else {
			return super.lookupFc(itfName);
		}
	}

	public void unbindFc(String itfName) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
		if (itfName.startsWith(handlersItfNamePrefix)) {
			if(!handlers.containsKey(itfName)) throw new NoSuchInterfaceException(itfName);
			handlers.remove(itfName);
		}else{ 
			super.unbindFc(itfName);
		}
	}
}
